package org.lee.hello.util;

import net.bytebuddy.dynamic.DynamicType;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

/**
 * @author jackielee
 * @version 1.0
 * @description ClassUtil
 * @date 2021/7/28
 **/
public class ClassUtil {

    public static void outputClass(byte[] bytes, String className) {
        String path = ClassUtil.class.getResource("/").getPath() + className + ".class";
        try (FileOutputStream out = new FileOutputStream(new File(path))) {
            out.write(bytes);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void runClass(DynamicType.Unloaded<?> dynamicType) {
        // 加载
        Class<?> clazz = dynamicType.load(ClassUtil.class.getClassLoader()).getLoaded();
        // 反射调用
        try {
            clazz.getMethod("main", String[].class).invoke(clazz.newInstance(), (Object) new String[0]);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }

}
